import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import {
  Row,
  Col,
  Card,
  TimePicker,
  Spin,
  Popconfirm,
  Tooltip,
  Button,
  Menu,
  Dropdown,
  Icon,
  DatePicker,
  Select,
  Modal,
} from 'antd';
import moment from 'moment';
// import Calendar from 'react-big-calendar/lib/Calendar'
import BigCalendar from 'react-big-calendar';
import withDragAndDrop from 'react-big-calendar/lib/addons/dragAndDrop';

// import 'react-big-calendar/lib/css/react-big-calendar.css';
// import 'react-big-calendar/lib/addons/dragAndDrop/styles.less';
import 'react-big-calendar/lib/addons/dragAndDrop/styles.css';
import 'react-big-calendar/lib/css/react-big-calendar.css';
import TeacherCalendarAddForm from './TeacherCalendarAddForm';
import TeacherCalendarUpdateForm from './TeacherCalendarUpdateForm';
import TeacherCalendarChangeSupplyTeacher from './TeacherCalendarChangeSupplyTeacher';
import TeacherCalendarSearchInput from './TeacherCalendarSearchInput';
import { getParamUrl, myMessage } from '../../utils/formatDataSource';
BigCalendar.momentLocalizer(moment)
//TODO 杨波 这里可能是错误的
// BigCalendar.setLocalizer(BigCalendar.momentLocalizer(moment));
const DnDCalendar = withDragAndDrop(BigCalendar);
@connect(({ classInfo3, administration3, loading }) => ({
  classInfo:classInfo3,
  administration:administration3,
  loading: loading.models.administration,
}))
class TeacherCalendar extends React.Component {
  constructor(props) {
    super(props);
    this.onEventDrop = this.onEventDrop.bind(this);
    this.onEventResize = this.onEventResize.bind(this);
    this.onSelectEvent = this.onSelectEvent.bind(this);
    this.onSelectSlot = this.onSelectSlot.bind(this);
  }
  state = {
    defaultDate: new Date(),
    events: [],
    selectedEvents: {},
    selectedEventMinutes: 0,
    selectBlankStart: null,
    selectBlankEnd: null,
    classList: [],
    teacherId: null,
    selectCampusId: null,
    selectClassType: null,
    campusList: [],
    copyWeekLessonVisible: false,
    navigateSelectDate: new Date(),
    batchDateRangeDateStart: null,
    batchDateRangeDateEnd: null,
    lessonDateFrom: null,
    lessonDateTo: null,
    lessonDefaultRange: [],
    workTimeVisible: false,
    workTimeStart: '07:00',
    workTimeEnd: '07:30',
    editDay: '',
    totalWorkTime: [],
    classTypeList: [],
  };
  transformDate = events => {
    for (var event of events) {
      event.start = moment(event.start).toDate();
      event.end = moment(event.end).toDate();
    }
    this.setState({
      events,
    });
  };
  componentWillMount() {
    const { location: { search } } = this.props;
    const params = getParamUrl(search);
    if (params && params.teacherId) {
      this.setState({
        teacherName: decodeURI(params.teacherName),
        selectCampusId: params.campusId,
        selectClassType: params.type,
        lessonDefaultRange: [moment(params.startDate), moment(params.endDate)],
        lessonDateFrom: params.startDate,
        lessonDateTo: params.endDate,
        defaultDate: moment(params.startDate).toDate(),
      });
    }
  }
  componentDidMount() {
    this.props
      .dispatch({
        type: 'classInfo3/getClassTypeList',
      })
      .then(() => {
        this.setState({
          classTypeList: this.props.classInfo.classTypeList,
        });
      });
    const { location: { search } } = this.props;
    const params = getParamUrl(search);
    if (params && params.teacherId) {
      this.props
        .dispatch({
          type: 'classInfo3/getClassTypeList',
        })
        .then(() => {
          this.setState({
            classTypeList: this.props.classInfo.classTypeList,
          });
        });
      this.setState(
        {
          teacherId: params.teacherId,
        },
        () => {
          this.initLoad(this.state.teacherId);
          this.loadLesson();
        }
      );
    }
  }

  // 根据老师获取如下信息： 老师对应的班级、老师对应的校区、老师对应的工作课时
  initLoad = teacherId => {
    if (!teacherId) {
      return;
    }
    const { dispatch, administration, location: { search } } = this.props;
    dispatch({
      type: 'administration3/getTeacherWorkTime',
      payload: {
        teacherId,
      },
    }).then(() => {
      const { worktime, classes, campus } = this.props.administration.totalWorkTime;
      worktime.map(w => {
        const { start, end } = w;
        w.start = moment(start, 'YYYY-MM-DD HH:mm')._d.getTime();
        w.end = moment(end, 'YYYY-MM-DD HH:mm')._d.getTime();
      });
      this.setState({
        totalWorkTime: worktime,
        classList: classes,
        campusList: campus,
      });
    });
  };
  loadLesson = () => {
    const { dispatch, administration, location: { search } } = this.props;
    const { selectCampusId, selectClassType, teacherId, lessonDateFrom, lessonDateTo } = this.state;
    if (!teacherId) {
      return;
    }
    dispatch({
      type: 'administration3/getTeacherLessonList',
      payload: {
        teacherId: teacherId,
        classType: selectClassType,
        campusId: selectCampusId,
        lessonDateFrom: lessonDateFrom,
        lessonDateTo: lessonDateTo,
      },
    }).then(() => {
      this.transformDate(this.props.administration.events);
    });
  };
  onEventResize = (type, { event, start, end, allDay }) => {
    const { selectedEvents, events } = this.state;
    const { dispatch } = this.props;
    const idx = events.indexOf(selectedEvents);
    const updatedEvent = { ...selectedEvents, start, end };
    const nextEvents = [...events];

    updatedEvent.id = event.id;
    //服务器加载更新
    dispatch({
      type: 'administration3/updateLessonDate',
      payload: updatedEvent,
    }).then(() => {
      const { updateLessonResponse } = this.props.administration;
      if (updateLessonResponse.data == 1) {
        nextEvents.splice(idx, 1, updatedEvent);
        myMessage.success('更新成功', 2);
        this.setState({
          events: nextEvents,
        });
      }
    });
  };
  onSelectEvent(event) {
    console.log(event);
    this.setState({ selectedEvents: event });
    const selectedStart = moment(event.start);
    const selectedEnd = moment(event.end);
    this.setState({
      selectedEventMinutes: selectedEnd.diff(selectedStart, 'minute'),
    });
  }
  onSelectSlot = event => {
    const { teacherId } = this.state;
    const { box } = event;
    if (event.action === 'doubleClick') {
      this.setState({ selectBlankStart: event.start, selectBlankEnd: event.end });
      this.setState({ addVisible: true });
    } else {
      if (teacherId && box) {
        const { start } = event;
        const editDay = moment(start).format('YYYY-MM-DD');
        this.setState({ editDay });
        let clickMenu = document.getElementById('clickMenu');
        clickMenu.style.left = box.x + 'px';
        clickMenu.style.top = box.y + 'px';
        clickMenu.style.display = 'block';
        clickMenu.style.position = 'absolute';
      }
    }
  };
  onEventDrop = ({ event, start, end, allDay }) => {
    const { events } = this.state;
    const { dispatch } = this.props;
    const idx = events.indexOf(event);
    const updatedEvent = { ...event, start, end };
    dispatch({
      type: 'administration3/updateLessonDate',
      payload: updatedEvent,
    }).then(() => {
      const { updateLessonResponse } = this.props.administration;
      if (updateLessonResponse.data == 1) {
        //   myMessage.success("修改成功",2);
        const nextEvents = [...events];
        nextEvents.splice(idx, 1, updatedEvent);
        this.setState({
          events: nextEvents,
        });
      }
    });
  };

  selectUpdateEventUi = () => {
    const { selectedEvents } = this.state;
    this.setState({ visible: true });
  };
  selectChangeTeacher = () => {
    const { selectedEvents } = this.state;
    this.setState({ changeVisible: true });
  };
  selectDeleteEvent = () => {
    const { selectedEvents, events } = this.state;
    const { dispatch } = this.props;
    const idx = events.indexOf(selectedEvents);
    const nextEvents = [...events];
    dispatch({
      type: 'administration3/removeLesson',
      payload: 'lessonId=' + selectedEvents.id,
    }).then(() => {
      // 返回刷新页面
      const { removeLessonResponse } = this.props.administration;
      if (removeLessonResponse.data == 1) {
        myMessage.success('删除成功', 2);
        nextEvents.splice(idx, 1);
        this.setState({
          events: nextEvents,
        });
      }
    });
  };
  menu = (
    <Menu>
      <Menu.Item key="0">
        <a onClick={this.selectUpdateEventUi}>修 改</a>
      </Menu.Item>
      <Menu.Divider />
      <Menu.Item key="1">
        <Popconfirm
          placement="top"
          title="确定删除？"
          onConfirm={this.selectDeleteEvent}
          okText="确定"
          cancelText="取消"
        >
          <a>删 除</a>
        </Popconfirm>
      </Menu.Item>
      <Menu.Item key="2">
        <a onClick={this.selectChangeTeacher}>代 课</a>
      </Menu.Item>
      {/*<Menu.Item key="2">*/}
      {/*<a>推荐时间</a>*/}
      {/*</Menu.Item>*/}
    </Menu>
  );
  eventUi = ({ event }) => {
    console.log(event);
    const lessonTeacherStatus = event.teacherId == event.classTeacherId ? '' : '（代）';
    return (
      <div id="selfDiv">
        <Tooltip
          placement="topLeft"
          title={
            event.className +
            ' ' +
            event.classTypeName +
            ' ' +
            event.classLevelName +
            ' ' +
            event.campusName +
            ' ' +
            lessonTeacherStatus
          }
          arrowPointAtCenter
        >
          <Row type="flex" align="middle">
            <Col span={24}>
              {event.className}
              {event.typeName ? ' ' + event.typeName : ''}
              {event.classLevelName ? ' ' + event.classLevelName : ''}
              {event.campusName ? ' ' + event.campusName : ''}
              {lessonTeacherStatus ? ' ' + lessonTeacherStatus : ''}
              &nbsp;&nbsp;
              <Dropdown overlay={this.menu} trigger={['click']}>
                <a className="ant-dropdown-link" href="#">
                  <Icon type="ellipsis" />
                </a>
              </Dropdown>
            </Col>
          </Row>
        </Tooltip>
      </div>
    );
  };
  handleCancel = () => {
    this.setState({ visible: false });
  };
  handleAddCancel = () => {
    this.setState({ addVisible: false });
  };
  handleAddCreate = events => {
    this.setState({ addVisible: false, events: events }, () => {
      this.loadLesson();
    });
  };
  handleChangModal = events => {
    this.setState({ changeVisible: false, events: events });
  };
  handleCreate = events => {
    this.setState({
      events: events,
    });
    this.setState({ visible: false });
  };
  handleChangeTeacher = events => {
    this.setState({
      changeVisible: false,
      events: events,
    });
  };
  handleChangeCancel = () => {
    this.setState({
      changeVisible: false,
    });
  };
  handleCopyWeekLesson = e => {
    const { dispatch } = this.props;
    const { teacherId, navigateSelectDate } = this.state;
    if (!teacherId) {
      myMessage.info('请选择老师', 5);
      return;
    }
    dispatch({
      type: 'administration3/checkLesson',
      payload: {
        teacherId: teacherId,
        currentDate: navigateSelectDate,
      },
    }).then(() => {
      const { checkLessonResponse } = this.props.administration;
      if (checkLessonResponse && checkLessonResponse.data == 1) {
        this.setState({
          copyWeekLessonVisible: true,
        });
      } else {
        myMessage.error('当前周不能存在课程', 5);
      }
    });
  };
  selectTeacher = selectTeacherId => {
    this.initLoad(selectTeacherId.id);
    this.setState(
      {
        teacherId: selectTeacherId.id,
      },
      () => {
        this.loadLesson();
      }
    );
  };
  navigateDate = (date, view, action) => {
    this.setState({
      navigateSelectDate: date,
      defaultDate: date,
    });
  };
  batchLessonChange = (date, dateStr) => {
    if (moment(date[0]).day() != 1) {
      myMessage.error('开始日期不是周一', 3);
      return;
    }
    if (moment(date[1]).day() != 0) {
      myMessage.error('结束日期不是周日', 3);
      return;
    }
    this.setState({
      batchDateRangeDateStart: date[0],
      batchDateRangeDateEnd: date[1],
    });
  };

  batchAddLessonOk = () => {
    const { dispatch } = this.props;
    const {
      teacherId,
      navigateSelectDate,
      batchDateRangeDateStart,
      batchDateRangeDateEnd,
    } = this.state;
    dispatch({
      type: 'administration3/batchAddLesson',
      payload: {
        teacherId: teacherId,
        currentDate: navigateSelectDate,
        startDate: batchDateRangeDateStart,
        endDate: batchDateRangeDateEnd,
      },
    }).then(() => {
      const { batchAddResponse } = this.props.administration;
      if (batchAddResponse && batchAddResponse.data == 1) {
        myMessage.success('批量生成成功', 5);
        this.setState({
          copyWeekLessonVisible: false,
        });
        this.loadLesson();
      } else {
        myMessage.error('批量生成失败', 5);
      }
    });
  };
  batchAddLessonCancel = () => {
    this.setState({
      copyWeekLessonVisible: false,
    });
  };
  publishTeacher = () => {
    const { dispatch } = this.props;
    const { teacherId } = this.state;
    if (!teacherId) {
      myMessage.error('请选择老师', 3);
      return;
    }
    dispatch({
      type: 'administration3/publishLesson',
      payload: 'teacherId=' + teacherId,
    }).then(() => {
      const { publishLessonResponse } = this.props.administration;
      if (publishLessonResponse && publishLessonResponse.data == 1) {
        myMessage.success('发布成功', 3);
      } else {
        myMessage.error('发布失败', 3);
      }
    });
  };
  campusSelect = value => {
    this.setState(
      {
        selectCampusId: value,
      },
      () => {
        this.loadLesson();
      }
    );
  };
  classTypeSelect = value => {
    this.setState(
      {
        selectClassType: value,
      },
      () => {
        this.loadLesson();
      }
    );
  };
  dateChange = (date, dateStr) => {
    this.setState(
      {
        lessonDateFrom: date[0],
        lessonDateTo: date[1],
      },
      () => {
        this.loadLesson();
      }
    );
  };
  mouseLeave = () => {
    var div = document.getElementById('clickMenu');
    div.style.display = 'none';
  };
  showTimeAdd = () => {
    const { totalWorkTime, editDay } = this.state;
    const exist = totalWorkTime.find(t => t.day === editDay);
    if (exist) {
      const workTimeStart = moment(exist.start).format('HH:mm');
      const workTimeEnd = moment(exist.end).format('HH:mm');
      this.setState({
        workTimeStart,
        workTimeEnd,
        workTimeVisible: true,
      });
    } else {
      this.setState({
        workTimeStart: '07:00',
        workTimeEnd: '07:30',
        workTimeVisible: true,
      });
    }
  };
  workTimeOk = () => {
    const { workTimeStart, workTimeEnd, editDay, totalWorkTime, teacherId } = this.state;
    const existOne = totalWorkTime.find(t => t.day === editDay);
    const editStart = editDay + ' ' + workTimeStart;
    const editEnd = editDay + ' ' + workTimeEnd;
    if (editEnd <= editStart) {
      myMessage.error('下班时间不能小于上班时间', 2);
      return;
    }
    this.props
      .dispatch({
        type: 'administration3/addWorkTime',
        payload: {
          id: existOne ? existOne.id : null,
          start: editStart,
          end: editEnd,
          day: editDay,
          userId: teacherId,
        },
      })
      .then(() => {
        const status = this.props.administration.response;
        if (status === 1) {
          myMessage.error('保存失败', 2);
          return;
        }
        const startTime = moment(editStart, 'YYYY-MM-DD HH:mm')._d.getTime();
        const endTime = moment(editEnd, 'YYYY-MM-DD HH:mm')._d.getTime();
        if (existOne) {
          existOne.start = startTime;
          existOne.end = endTime;
        } else {
          const newOne = {
            id: null,
            day: editDay,
            start: startTime,
            end: endTime,
          };
          totalWorkTime.push(newOne);
        }
        this.setState({
          workTimeVisible: false,
          totalWorkTime: [...totalWorkTime],
        });
      });
  };
  workTimeCancel = () => {
    this.setState({ workTimeVisible: false });
  };
  workTimeStartChange = e => {
    this.setState({ workTimeStart: e });
  };
  workTimeEndChange = e => {
    this.setState({ workTimeEnd: e });
  };
  propGetter = date => {
    const { totalWorkTime } = this.state;
    const edg = moment(date, 'YYYY-MM-DD HH:mm');
    const today = edg.format('YYYY-MM-DD');
    const minis = edg._d.getTime();
    const exist = totalWorkTime.find(t => t.day === today);
    if (exist) {
      if (minis >= exist.start && minis < exist.end) {
        return {
          style: {
            width: '100%',
            backgroundColor: '#b7eb8f',
          },
        };
      }
    }
  };
  getWorkTimeEnum = () => {
    return [
      '07:00',
      '07:30',
      '08:00',
      '08:30',
      '09:00',
      '09:30',
      '10:00',
      '10:30',
      '11:00',
      '11:30',
      '12:00',
      '12:30',
      '13:00',
      '13:30',
      '14:00',
      '14:30',
      '15:00',
      '15:30',
      '16:00',
      '16:30',
      '17:00',
      '17:30',
      '18:00',
      '18:30',
      '19:00',
      '19:30',
      '20:00',
      '20:30',
      '21:00',
      '21:30',
      '22:00',
      '22:30',
    ];
  };

  render() {
    const { RangePicker } = DatePicker;
    const { Option } = Select;
    const { campusList, teacherName, defaultDate } = this.state;
    const minTime = new Date();
    minTime.setHours(7, 0, 0);
    const maxTime = new Date();
    maxTime.setHours(23, 0, 0);
    const timeArr = this.getWorkTimeEnum();

    return (
      <div>
        <Card>
          <Row>
            <Col span={4}>
              老师名称：<TeacherCalendarSearchInput
                teacherName={teacherName}
                myStyle={150}
                span={24}
                subject=""
                onOk={this.selectTeacher}
              />
            </Col>
            <Col span={3}>
              <Select
                placeholder="请选择校区"
                style={{ width: '80%' }}
                value={this.state.selectCampusId || ''}
                onSelect={this.campusSelect}
              >
                <Option value="">全部校区</Option>
                {campusList.map((item, index) => {
                  return (
                    <Option key={index} value={item.id + ''}>
                      {item.name}
                    </Option>
                  );
                })}
              </Select>
            </Col>
            <Col span={3}>
              <Select
                placeholder="请选择课类型"
                style={{ width: '80%' }}
                defaultValue={this.state.selectClassType || ''}
                onSelect={this.classTypeSelect}
              >
                <Option value="">全部</Option>
                {this.state.classTypeList.map(t => (
                  <Option value={t.id} key={t.id}>
                    {t.name}
                  </Option>
                ))}
              </Select>
            </Col>
            {/* <Col span={4}>
                    <RangePicker span={12} defaultValue={this.state.lessonDefaultRange} onChange={this.dateChange}  />
                   </Col> */}
            <Col style={{ textAlign: 'right' }}>
              <Button type="primary" onClick={this.publishTeacher}>
                发布
              </Button>&nbsp;&nbsp;
              <Button onClick={this.handleCopyWeekLesson} type="primary">
                复制一周课程
              </Button>
            </Col>
          </Row>
        </Card>
        {/* <Button onClick={this.handleCopyWeekLesson}>复制一周课程</Button> */}
        <Spin
          tip="Loading..."
          spinning={this.props.loading === undefined ? false : this.props.loading}
        >
          <DnDCalendar
            selectable
            date={defaultDate}
            onNavigate={this.navigateDate}
            messages={{ today: '今日', previous: '上周', next: '下周' }}
            defaultView="week"
            events={this.state.events}
            onEventDrop={this.onEventDrop}
            onEventResize={this.onEventResize}
            resizable
            onSelectEvent={this.onSelectEvent}
            onSelectSlot={this.onSelectSlot}
            min={minTime}
            max={maxTime}
            style={{ height: '100vh' }}
            views={['week']}
            components={{
              event: this.eventUi,
            }}
            slotPropGetter={this.propGetter}
          />
        </Spin>
        <TeacherCalendarUpdateForm
          onOk={this.handleCreate}
          onCancel={this.handleCancel}
          selectedEventMinutes={this.state.selectedEventMinutes}
          events={this.state.events}
          updateVisible={this.state.visible}
          selectedEvents={this.state.selectedEvents}
        />
        <TeacherCalendarAddForm
          onOk={this.handleAddCreate}
          onCancel={this.handleAddCancel}
          selectBlankStart={this.state.selectBlankStart}
          events={this.state.events}
          addVisible={this.state.addVisible}
          selectedEvents={this.state.selectedEvents}
          classList={this.state.classList}
        />
        <TeacherCalendarChangeSupplyTeacher
          myStyle={150}
          onOk={this.handleChangeTeacher}
          onCancel={this.handleChangeCancel}
          events={this.state.events}
          supplyVisible={this.state.changeVisible}
          selectedEvents={this.state.selectedEvents}
        />
        <Modal
          title="选择时间段"
          visible={this.state.copyWeekLessonVisible}
          onOk={this.batchAddLessonOk}
          onText="生成"
          onCancel={this.batchAddLessonCancel}
        >
          <div>请生成时间段(周一开始周日结束)：</div>
          <div>
            <RangePicker
              disabledDate={disabledTimeArray}
              span={12}
              onChange={this.batchLessonChange}
            />
          </div>
        </Modal>
        <div
          id="clickMenu"
          style={{
            display: 'none',
            backgroundColor: '#fff',
            backgroundClip: 'paddingBox',
            borderRadius: '4px',
            boxShadow: '0 2px 8px rgba(0, 0, 0, 0.15)',
          }}
          onMouseLeave={this.mouseLeave}
        >
          <ul
            className="ant-dropdown-menu ant-dropdown-menu-light ant-dropdown-menu-root ant-dropdown-menu-vertical"
            role="menu"
          >
            <li className="ant-dropdown-menu-item" role="menuitem">
              <a href="javascript:;" onClick={this.showTimeAdd}>
                编辑工时
              </a>
            </li>
          </ul>
        </div>
        <Modal
          title="编辑工时"
          visible={this.state.workTimeVisible}
          onOk={this.workTimeOk}
          onText="生成"
          onCancel={this.workTimeCancel}
        >
          {/* <Row type='flex' align='middle'>
                <Col span={12}>上班时间：<TimePicker value={this.state.workTimeStart} format='HH:mm' onChange={this.workTimeStartChange}/></Col>
                <Col span={12}>下班时间：<TimePicker value={this.state.workTimeEnd} format='HH:mm' onChange={this.workTimeEndChange}/></Col>
              </Row> */}
          <Row type="flex" align="middle">
            <Col span={12}>
              上班时间：
              <Select value={this.state.workTimeStart} onChange={this.workTimeStartChange}>
                {timeArr.map((t, i) => (
                  <Option value={t} key={i}>
                    {t}
                  </Option>
                ))}
              </Select>
            </Col>
            <Col span={12}>
              下班时间：
              <Select value={this.state.workTimeEnd} onChange={this.workTimeEndChange}>
                {timeArr.map((t, i) => (
                  <Option value={t} key={i}>
                    {t}
                  </Option>
                ))}
              </Select>
            </Col>
          </Row>
        </Modal>
      </div>
    );
  }
}
function disabledTimeArray(current) {
  return (current && current < moment().endOf('day')) || (current.day() != 0 && current.day() != 1);
}


export default TeacherCalendar;
